package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constants.ProductConstants;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
@Slf4j
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttrVo(AttrVo attrVo) {
        //保存属性表基本数据
        this.save(attrVo);
        if(attrVo.getAttrType() == ProductConstants.AttrEnum.ATTR_BASE_TYPE.getCode() && attrVo.getAttrGroupId() != null ){
            //保存属性对应分组关联表
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrVo.getAttrId());
            relationService.save(attrAttrgroupRelationEntity);
        }
    }

    /**
     * 查询基本属性列表
     */
    @Override
    public PageUtils attrList(Map<String, Object> params, Long catelogId, String attrType) {
        LambdaQueryWrapper<AttrEntity> queryWrapper = new LambdaQueryWrapper<AttrEntity>();
        //添加类型过滤条件  1：基本数据 0：销售信息
        queryWrapper.eq(AttrEntity::getAttrType,attrType.equalsIgnoreCase("base")? ProductConstants.AttrEnum.ATTR_BASE_TYPE.getCode() : ProductConstants.AttrEnum.ATTR_SALE_TYPE.getCode());
        String key = (String) params.get("key");
        //添加分类id 条件
        log.info("属性条查Key{}", key);
        if(catelogId != 0){
            queryWrapper.eq(AttrEntity::getCatelogId,catelogId);
        }
        //加入条查

        if(StringUtils.isNotBlank(key)){
            log.info("进入属性条查：{}",key);
            queryWrapper.and((obj)->{
                obj.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> collect = records.stream().map(attr -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attr, attrRespVo);

            //查找对应属性的 分组名
            if(attrType.equalsIgnoreCase("base")){
                AttrAttrgroupRelationEntity one = relationService.getOne(
                        new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()));
                if(one != null && one.getAttrGroupId() != null){
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(one.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());

                }
            }

            //，和所属菜单名
            CategoryEntity categoryEntity = categoryService.getById(attr.getCatelogId());
            if(categoryEntity != null){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrVo(Long attrId) {
        AttrRespVo attrVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrVo);

        if(attrEntity.getAttrType() == ProductConstants.AttrEnum.ATTR_BASE_TYPE.getCode()){
            //获取当前属性分组 关联表数据
            AttrAttrgroupRelationEntity  attrAttrgroupRelation = relationService.getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId()));
            if(attrAttrgroupRelation != null){
                //分组ID
                attrVo.setAttrGroupId(attrAttrgroupRelation.getAttrGroupId());
                //获取分组名称
                AttrGroupEntity byId = attrGroupService.getById(attrAttrgroupRelation.getAttrGroupId());
                if(byId != null){
                    attrVo.setGroupName(byId.getAttrGroupName());
                }
            }
        }

        //设置分类数据
        Long[] catelogPath = categoryService.getCatelogPath(attrEntity.getCatelogId());
        attrVo.setCatelogPath(catelogPath);

        CategoryEntity byId = categoryService.getById(attrEntity.getCatelogId());
        attrVo.setCatelogName(byId.getName());
        return attrVo;
    }


    @Override
    public void updateAttrvo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //修改属性基本信息
        this.updateById(attrEntity);

        if(attr.getAttrType() == ProductConstants.AttrEnum.ATTR_BASE_TYPE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attr,attrAttrgroupRelationEntity);
            //查看当前属性  关联表是否存在， 命中修改，未命中新增
            int count = relationService.count(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,attr.getAttrId()));
            if(count > 0){
                //修改属性对应的  属性分组关联表信息。
                LambdaUpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(AttrAttrgroupRelationEntity::getAttrId,attr.getAttrId());
                relationService.update(attrAttrgroupRelationEntity,updateWrapper);
            }else{
                relationService.save(attrAttrgroupRelationEntity);
            }
        }


    }

    @Override
    public PageUtils getNoattrRelation(Long attrGroupId, Map<String, Object> params) {
        //1. 当前分组只能关联自己所属的分类里面的所有属性

        //1.1 查找当前分组的 分类 在查找分类下所有已经关联的属性
        AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);
        //分类ID
        Long catelogId = attrGroup.getCatelogId();

        //分类ID 的所有分组
        List<AttrGroupEntity> attrGroups = attrGroupService.list(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getCatelogId, catelogId));
        List<Long> groupIds = attrGroups.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //获取分组所关联的所有属性
        LambdaQueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<>();
        if(groupIds != null && groupIds.size() > 0){
            queryWrapper.in(AttrAttrgroupRelationEntity::getAttrGroupId,groupIds);
        }
        //获取属性关联表
        List<AttrAttrgroupRelationEntity> relationEntitys = relationService.list(queryWrapper);
        //获取到当前分类 所有分组所关联的属性ID
        List<Long> attrIds = relationEntitys.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2. 当前分组只能关联别的分组没有引用的属性                               //设置只能是基本属性过滤条件
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>().eq(AttrEntity::getAttrType,ProductConstants.AttrEnum.ATTR_BASE_TYPE.getCode());
        wrapper.eq(AttrEntity::getCatelogId,catelogId);

        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(w->{
                w.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
            });
        }

        if(attrIds != null && attrIds.size() > 0){
            wrapper.notIn(AttrEntity::getAttrId,attrIds);
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    //在指定的属性集合里面，挑出检索属性
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        LambdaQueryWrapper<AttrEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(AttrEntity::getAttrId);
        queryWrapper.eq(AttrEntity::getSearchType,1);
        queryWrapper.in(AttrEntity::getAttrId,attrIds);
        List<Object> objects = this.baseMapper.selectObjs(queryWrapper);
        List<Long> collect = objects.stream().map(item -> {
            return Long.parseLong(item.toString());
        }).collect(Collectors.toList());
        return collect;
    }


}